package com.yhsimon.realm.member.controller;

import com.yhsimon.realm.member.entity.article.ArticleEntity;
import com.yhsimon.realm.member.service.ArticleService;
import com.yhsimon.realm.member.utils.R;
import com.yhsimon.realm.member.vo.article.ArticleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/member/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    /**
     * 查询文章
     */
    @GetMapping("/listArticleAll")
    public R listArticleAll() {
        List<ArticleVo> articleList = articleService.listArticleAll();
        return R.ok().put("data", articleList);
    }


    /**
     * 查询用户的所有已发表文章
     */
    @GetMapping("/listArticleByUserId/{userId}")
    public R listArticleByUserId(@PathVariable String userId) {
        List<ArticleVo> articleList = articleService.listArticleByUserId(Long.parseLong(userId));
        return R.ok().put("data", articleList);
    }


    /**
     * 查询用户的所有草稿文章
     */
    @GetMapping("/listArticleDraftByUserId/{userId}")
    public R listArticleDraftByUserId(@PathVariable String userId) {
        List<ArticleVo> articleDraftList = articleService.listArticleDraftByUserId(Long.parseLong(userId));
        return R.ok().put("data", articleDraftList);
    }


    /**
     * 查询文章详情
     */
    @GetMapping("/listArticleById")
    public R listArticleById(@RequestParam("id") String id, @RequestParam("userId") String userId) {
        R r = articleService.listArticleById(Long.parseLong(id), userId);
        return r;
    }

    /**
     * 保存或更新文章
     */
    @PostMapping("/saveArticle")
    public R saveArticle(@RequestBody ArticleEntity article) {
        article.setStatus(0);
        if (article.getId() != null && articleService.existsArticle(article.getId())) {
            article.setUpdateTime(new Date());
            articleService.updateById(article);
            return R.ok("文章更新成功！");
        } else {
            articleService.save(article);
            return R.ok("文章发布成功！");
        }
    }

    /**
     * 保存或更新文章
     */
    @PostMapping("/saveArticleDraft")
    public R saveArticleDraft(@RequestBody ArticleEntity article) {
        article.setStatus(1);
        if (article.getId() != null && articleService.existsArticle(article.getId())) {
            article.setUpdateTime(new Date());
            articleService.updateById(article);
            return R.ok("草稿更新成功！");
        } else {
            articleService.save(article);
            return R.ok("草稿保存成功！");
        }
    }

    /**
     * 点赞文章
     */
    @GetMapping("/likeArticle")
    public R likeArticle(@RequestParam(name = "id") String id, @RequestParam(name = "userId") String userId) {
        articleService.likeArticle(id, userId);
        return R.ok();
    }


}
